package com.neuedu.predicates;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

@Component
public class AdminRoutePredicateFactory extends AbstractRoutePredicateFactory<AdminRoutePredicateFactory.Config> {

    // 配置参数键名
    private static final String VALUE_KEY = "value";

    public AdminRoutePredicateFactory() {
        super(Config.class);
    }

    // 读取配置文件中的参数值
    @Override
    public List<String> shortcutFieldOrder() {
        // 只需要一个参数：期望的admin值
        return Collections.singletonList(VALUE_KEY);
    }

    // 断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                // 1. 获取请求参数中的admin值
                String adminValue = exchange.getRequest().getQueryParams().getFirst("admin");

                // 2. 验证参数是否存在且匹配配置值
                if (adminValue != null) {
                    return adminValue.equals(config.getValue());
                }

                return false;
            }
        };
    }

    // 配置类（内部类）
    public static class Config {
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}